<?php

class ProductController extends HBaseController
{ 

	public function actionIndex()
	{
		//设置首页导航焦点
		$this->active_cur = 'home';
        $condition = 't.zp_status = 2 AND t.zp_state = 2 ';
        $orderby = 't.zp_sale_num DESC';
        $criteria = new CDbCriteria(array(
                    'condition' => $condition,                    
                    'order' => $orderby.', t.zp_id DESC',                                  
                ));
		//统计产品数量
        $count = Product::model()->count($criteria,array('select' =>'zp_id'));
        $pages = new CPagination($count);
        // results per page
        $pages->pageSize = 20;
        $pages->applyLimit($criteria);
        $items = Product::model()->findAll($criteria);     
        $cid = 0;   
        $this->render('list', array(
            'items' => $items,                        //产品
            'att' => $att,                            //属性
            'cid'=>$cid,                             //子ID
            'pages' => $pages,                        //分页            
            'total'=>$count,                          //统计
            'categorys' => Category::model()->GetCategorys(),  //分类缓存
            'category' => Category::model()->GetCatCache()     //左侧分类缓存
        ));
	}

    
	//产品列表
	public function actionList($id){
		//设置首页导航焦点
		$this->active_cur = 'pro_list_'.$id;
		$model = new Product();
		$model->unsetAttributes();//清空属性
		
		$model->zp_status = 2;//审核通过
		$model->zp_state = 2;//上架
		
		//行业分类ID
		if(isset($_GET['id'])){
			$model->catgory_id = (int)$_GET['id'];
		}
		        
        //属性
        if(isset($_REQUEST['att'])&&!empty($_REQUEST['att'])){
        	//格式化属性数据
			$model->att = explode('-',$_REQUEST['att']);
        }
        //查询价格区间
        if (isset($_REQUEST['price'])) {
            $model->price_level = (int)$_GET['price'];
        }
        //查询关键词
        if (isset($_REQUEST['keyword'])) {
            $model->keyword = trim($_REQUEST['keyword']);            
        }
        //排序
        if(isset($_GET['sort'])){
			$model->list_order = $_GET['sort'];
        }

		$cat = Category::model()->findByPk($id);
		
		$page = isset($_GET['Product_page'])?"-第".$_GET['Product_page']."页":"";
        //SEO信息
        $this->pageTitle   = !empty($cat->attributes['zca_seotitle'])?$cat->attributes['zca_seotitle'].$page."-".Yii::app()->name:$cat->attributes['zca_title'].$page."-".Yii::app()->name; //SEO标题
		$this->pageKeyword = !empty($cat->attributes['zca_seokey'])?$cat->attributes['zca_seokey']:$cat->attributes['zca_title'];   //SEO关键字
		$this->pageDesc    = !empty($cat->attributes['zca_seodesc'])?$cat->attributes['zca_seodesc']:$cat->attributes['zca_title'];  //SEO描述        
 
        $this->render('list', array(
       		"g_att"=>isset($_REQUEST['att'])?$_REQUEST['att']:"",
            'model'=>$model,
        ));
	}

	//产品详细页
    public function actionDetail(){
    	if(!empty($_GET['id'])){
    		$id = $_GET['id'];
    		$active = !empty($_GET['active'])?$_GET['active']:'';
    		$productinfo = Product::GetInfoByid($id);//产品详细    			
			$this->pageTitle   = !empty($productinfo['zp_seotitle'])?$productinfo['zp_seotitle'].'-'.Yii::app()->name:$productinfo['zp_name'].'-'.Yii::app()->name; //SEO标题
			$this->pageKeyword = $productinfo['zp_seokey'];   //SEO关键字
			$this->pageDesc    = $productinfo['zp_seodesc'];  //SEO描述
    		$category = new Category(); 

    		//AJAX调用规格参数
    		$k = count($productinfo['spe']);    		
    		if( $k > 0 ){
    			$ajaxspe = "+\"&spe=\"";
    		}    		
    		for( $i=1; $i <= $k ; $i++ ) {     			
    			if( $k == $i){
    				$ajaxspe .= "+spe".$i;  
    			}else{
    				$ajaxspe .= "+spe".$i."+\":\"";   				
    			}    			
    		}
            //取所有的规格ID
            $speids = array();
            foreach ($productinfo['spe'] as $key => $value) {
                $speids[] =$key;
            }
            //月成交记录
            $dataProvider = new CActiveDataProvider('OrdProduct', array(
                'criteria'=>array(
                        'with'=>array('order'),
                        'condition'=>'zo_status=3 AND zp_id='.$id,
                    ),
                'pagination'=>array(
                    'pageSize'=>20,
                    'pageVar' => 'page',
                ),
                'sort' => array(
                    'defaultOrder' => 'zo_voer_time DESC'
                )
            ));

            //更新产品浏览量
            $product = Product::model()->findByPk($id);
            $product->zp_hits = $product->zp_hits+1;
            $product->save();
            
    		//添加用户浏览记录
    		MemHistory::model()->createBrowsingHistory($id);   
            //所有评论条数
            $comments = OrdComment::model()->countByAttributes(array('zoc_view'=>1,'zoc_type' =>2 ,'zp_id'=>$productinfo['zp_id']));
    		$this->render('detail',array(
    				'productinfo'=>$productinfo,
                    'comments'=>$comments,
    				'ajaxspe'=>isset($ajaxspe)?$ajaxspe:"",
                    'speids' =>implode(',', $speids), 				
    				'category'=>$category->GetCatCache(),                    
                    'active'=>$active,
    				'dataProvider'=>$dataProvider
    				));
    	}    	
    }
	
	//产品搜索
	public function actionSearch()
	{
        $keyword = !empty($_REQUEST['keyword'])?$_REQUEST['keyword']:'';
		$keyword = trim($keyword);
        
        $model = new Product();
        $model->unsetAttributes();
        $model->zp_status = 2;
        $model->zp_state = 2;
        $model->keyword = $keyword;
        $model->list_order = 4 ;

        //查询价格区间
        if (isset($_REQUEST['price'])) {
            $model->price_level = (int)$_GET['price'];
        }
        //查询关键词
        if (isset($_REQUEST['keyword'])) {
            $model->keyword = trim($_REQUEST['keyword']);
        }
        //排序
        if(isset($_GET['sort'])){
            $model->list_order = $_GET['sort'];
        }

        //SEO信息
        $this->pageTitle   = $keyword.' - 搜索 - '.Yii::app()->name; //SEO标题
        //$this->pageKeyword = $cat->attributes['zca_seokey'];   //SEO关键字
        //$this->pageDesc    = $cat->attributes['zca_seodesc'];  //SEO描述

		//添加搜索记录 start
        $search_num =SearchLog::model()->count("zsl_keyword=:keyword",array(":keyword"=>$keyword));
        if($search_num != 0)
        {
            $search_count = SearchLog::model()->updateAll(
                    array('updatetime'=>time(), 'zsl_ip'=>Yii::app()->request->getUserHostAddress(), 'zm_id'=>Yii::app()->user->id),
                    'zsl_keyword=:keyword',
                    array(':keyword'=>$keyword)
            );
        }
        else
        {
            $searchlog = new SearchLog;
            $searchlog->zsl_keyword = $keyword;
            $searchlog->zsl_num = $count;
            $searchlog->inputtime = time();
            $searchlog->zsl_ip = Yii::app()->request->getUserHostAddress();
            $searchlog->zm_id = Yii::app()->user->id;

            $type = !empty($_GET['type'])?$_GET['type']:0;
            switch($type)
            {
                case "0":
                    $searchlog->zsl_type = 'product';
                    break;
            }
            $searchlog->save();
        }
        //添加搜索记录 end

        $this->render('search',array(
            'model'=>$model,
            'keyword'=>$keyword,
    		'categorys' => Category::model()->GetCategorys(),  //分类缓存
            'category' => Category::model()->GetCatCache()     //左侧分类缓存
        ));
	}

    /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	

	
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
  
}